package com.p7.architect.store.shoppingcart.application.query;

import cn.hutool.core.collection.CollectionUtil;
import com.p7.architect.store.shoppingcart.application.command.dto.ShoppingCartDto;
import com.p7.architect.store.shoppingcart.application.converter.ShoppingCartDtoConverter;
import com.p7.architect.store.shoppingcart.domain.model.shoppingcart.ShoppingCart;
import com.p7.architect.store.shoppingcart.domain.model.shoppingcart.ShoppingCartRepository;
import com.p7.architect.store.shoppingcart.domain.model.shoppingcart.ShoppingItem;
import com.p7.architect.store.shoppingcart.domain.model.value.SkuId;
import com.p7.architect.store.shoppingcart.infrastructure.repositoryimpl.SkuRepositoryImpl;
import com.p7.architect.store.shoppingcart.infrastructure.repositoryimpl.vo.Sku;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class ShoppingCartInfoQueryService {

    private final ShoppingCartRepository shoppingCartRepository;

    private final ShoppingCartDtoConverter shoppingCartDtoConverter;

    private final SkuRepositoryImpl skuRepositoryImpl;

    public ShoppingCartDto queryWithCartId(ShoppingCartInfoQuery shoppingCartInfoQuery) {
        ShoppingCart shoppingCart = shoppingCartRepository.findById(shoppingCartInfoQuery.getShoppingCartId());
        return getShoppingCartDto(shoppingCart);
    }

    public ShoppingCartDto queryWithUserIdAndStoreId(ShoppingCartInfoQuery shoppingCartInfoQuery) {
        ShoppingCart shoppingCart = shoppingCartRepository.findByUserIdAndStoreId(
                shoppingCartInfoQuery.getUserId(), shoppingCartInfoQuery.getStoreId());
        return getShoppingCartDto(shoppingCart);
    }

    @Nullable
    private ShoppingCartDto getShoppingCartDto(ShoppingCart shoppingCart) {
        if (null == shoppingCart || null == shoppingCart.getShoppingCartId()) {
            log.info("ShoppingCartInfoQueryService#getShoppingCartDto shoppingCart is null.");
            return null;
        }
        List<Long> skuIds = shoppingCart.getItems().stream()
                .map(ShoppingItem::getSkuId)
                .map(SkuId::getId)
                .collect(Collectors.toList());

        if (CollectionUtil.isEmpty(skuIds)) {
            log.info("ShoppingCartInfoQueryService#getShoppingCartDto skuIds is null.");
            return null;
        }
        List<Sku> skus = skuRepositoryImpl.findSkuListBySkuIdList(skuIds);
        return shoppingCartDtoConverter.converterToShoppingCartDto(shoppingCart, skus);
    }
}
